package com.example.springbootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import java.io.IOException;
import jakarta.servlet.http.HttpServletResponse;
import com.alibaba.excel.EasyExcel;
import org.springframework.beans.factory.annotation.Autowired;

import com.example.springbootdemo.model.User;
import com.example.springbootdemo.service.UserService;

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    private final UserService userService;
    
    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }
    
    @GetMapping
    public List<User> getUsers() {
        return userService.getAllUsers();
    }

    @GetMapping("/export")
    public void exportUsers(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"users.xlsx\"");
        
        EasyExcel.write(response.getOutputStream(), User.class)
                .sheet("用户列表")
                .doWrite(userService.getAllUsers());
    }
}